<template>
	<view class="reset-container">
		<uni-forms ref="resetForm" :modelValue="formData" :rules="rules">
			<uni-forms-item label="原密码" name="oldPassword">
				<uni-easyinput v-model="formData.oldPassword" type="password" placeholder="请输入原密码" />
			</uni-forms-item>
			<uni-forms-item label="新密码" name="newPassword">
				<uni-easyinput v-model="formData.newPassword" type="password" placeholder="请输入新密码" />
			</uni-forms-item>
			<uni-forms-item label="确认新密码" name="confirmPassword">
				<uni-easyinput v-model="formData.confirmPassword" type="password" placeholder="请再次输入新密码" />
			</uni-forms-item>
		</uni-forms>
		<view class="submit-btn">
			<button type="primary" @click="submitReset">修改密码</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		resetPassword
	} from '@/api/user' // 你可以根据实际接口路径引入

	const resetForm = ref(null)
	const formData = ref({
		oldPassword: '',
		newPassword: '',
		confirmPassword: ''
	})

	const rules = {
		oldPassword: {
			rules: [{
				required: true,
				errorMessage: '请输入原密码'
			}]
		},
		newPassword: {
			rules: [{
					required: true,
					errorMessage: '请输入新密码'
				},
				{
					minLength: 6,
					errorMessage: '新密码不能少于6位'
				}
			]
		},
		confirmPassword: {
			rules: [{
					required: true,
					errorMessage: '请确认新密码'
				},
				{
					validateFunction: (rule, value, data, callback) => {
						if (value !== data.newPassword) {
							callback('两次输入的新密码不一致')
						}
						return true
					}
				}
			]
		}
	}

	const submitReset = async () => {
		try {
			const valid = await resetForm.value.validate()
			if (!valid) return

			uni.showLoading({
				title: '提交中...'
			})

			const res = await resetPassword({
				userId: uni.getStorageSync('userId'),
				oldPassword: formData.value.oldPassword,
				newPassword: formData.value.newPassword
			})
			uni.hideLoading()
			if (res.code === 200) {
				uni.showToast({
					title: '修改成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}, 1500)
			} else {
				uni.showToast({
					title: res.message || '修改失败',
					icon: 'none'
				})
			}
		} catch (error) {
			uni.hideLoading()
			uni.showToast({
				title: error.message || '修改失败',
				icon: 'none'
			})
		}
	}
</script>

<style>
	.reset-container {
		padding: 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	:deep(.uni-forms) {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;
	}

	:deep(.uni-forms-item) {
		padding: 10rpx 0;
	}

	.submit-btn {
		margin-top: 40rpx;
		padding: 0 20rpx;
	}

	.submit-btn button {
		width: 100%;
	}
</style>